package com.zhangx.datastructure.stacklist;

import java.util.Arrays;

/**
 * @ClassName SharedStack
 * @Description 两栈共享空间P96
 * 1 数据类型相同
 * 2 数据要有此消彼长的特性
 * @Author zhangx
 * @Date 2020/12/31 8:34
 **/
public class SharedStack {

    private int MAX_SIZE = 10;
    private int[] data = new int[10];
//    左侧开始
    private int top1 = -1;
//    右侧开始
    private int top2 = MAX_SIZE;

    public void push(int stackNum,int num){
        if (top1 + 1 == top2){
            System.out.println("栈溢出");
            return;
        }

        if (stackNum == 1){
//            左侧的栈
            data[++top1] = num;
        }
        if (stackNum == 2){
            data[--top2] = num;
        }
    }

    @Override
    public String toString() {
        return "SharedStack{" +
                "MAX_SIZE=" + MAX_SIZE +
                ", data=" + Arrays.toString(data) +
                ", top1=" + top1 +
                ", top2=" + top2 +
                '}';
    }

    public int pop(int stackNum){
        int result = -99;
        if (stackNum == 1){
            if (top1 == -1){
                System.out.println("溢出");
                return -1;
            }
            result = data[top1];
            data[top1] = 0;
            top1 --;
        }
        if (stackNum == 2){
            if (stackNum == MAX_SIZE){
                System.out.println("溢出");
                return -2;
            }
            result = data[top2];
            data[top2] = 0;
            top2++;
        }
        return result;
    }

    public static void main(String[] args) {
        SharedStack sharedStack = new SharedStack();
        sharedStack.push(1,9);
        System.out.println(sharedStack);
        sharedStack.push(2,8);
        System.out.println(sharedStack);
        System.out.println(sharedStack.pop(1));
        System.out.println(sharedStack);
        System.out.println(sharedStack.pop(2));
        System.out.println(sharedStack);
    }
}
